package cn.itcast.controller;

import cn.itcast.model.User;
import cn.itcast.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhaojie
 * @Date: Created in 15:31 2018/4/24
 * @Description: 在Service 的实现类中添加业务缓存 即可将数据保存到缓存 下次根据key取缓存
 * @Modified By:
 */
@RestController
@RequestMapping(path = "/user")
public class UserController {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 读取缓存  测试成功
     */
    @RequestMapping("/cache/{keys}")
    public Object getCache(@PathVariable("keys") String keys) {
        Object value = redisUtil.get(keys);
        return value;
    }

    /**
     * @Author: zhaojie
     * @Date 16:10 2018/4/24
     * @Description: 写入缓存 测试成功
     */
    @RequestMapping("/put/{keys}/{value}")
    public String putCache(@PathVariable("keys") String keys, @PathVariable("value") String value) {
        redisUtil.set(keys, value);
        return "存入成功";
    }

    @RequestMapping("/findall/{keys}")
    public String findall(@PathVariable("keys") String keys) {

        if (redisUtil.lGetListSize(keys) == 0) {
            //设置
            List<User> uses = new ArrayList<>();
            for (int i = 0; i < 10000; i++) {
                User use = new User();
                use.setId(String.valueOf(i));
                use.setName(i + "：hello");
                uses.add(use);
            }
            redisUtil.lSet(keys, uses, 2000);
            return "没有返回先查数据库";
        } else {
            //直接返回
            List rl = redisUtil.lGet(keys, 0, 10);
            long len = redisUtil.lGetListSize(keys);
            //2、使用JSONArray
            String actual = JSON.toJSONString(rl);
            return len + "查询缓存返回结果" + actual;
        }
    }

    /**
     * @Author: zhaojie
     * @Date 16:14 2018/4/24
     * @Description: 删除缓存
     */
    @RequestMapping("/removen/{keys}")
    public String remove(@PathVariable("keys") String keys) {
        redisUtil.remove(keys);
        return "删除成功";
    }


    /**
     * 缓存同步
     */
    @RequestMapping("/delete/{keys}")
    public String delete(@PathVariable("keys") String keys) {
        //如果数据没在缓存中 要将新的数据插入进去
        return "";
    }
}
